package user

import (
	"gitee.com/lidongyooo/goblog/pkg/logger"
	"gitee.com/lidongyooo/goblog/pkg/model"
	"gitee.com/lidongyooo/goblog/pkg/types"
)
func (u *User) Update() (rowsAffected int64, err error) {
	result := model.DB.Save(&u)

	if err = result.Error; err != nil {
		logger.LogError(err)
		return 0, err
	}

	return result.RowsAffected, nil
}

func (u *User) Create() (err error) {
	if err = model.DB.Create(&u).Error; err != nil {
		logger.LogError(err)
		return err
	}

	return nil
}

func GetByEmail(email string) (User, error) {
	var user User

	if err := model.DB.Where("email = ?", email).First(&user).Error; err != nil {
		return user, err
	}

	return user, nil
}

func GetByActivationToken(activationToken string) (User, error) {
	var user User

	if err := model.DB.Where("activation_token = ?", activationToken).First(&user).Error; err != nil {
		return user, err
	}

	return user, nil
}

func Get(idstr string) (User, error) {
	var user User
	id := types.StringToInt(idstr)

	if err := model.DB.First(&user, id).Error; err != nil {
		return user, err
	}

	return user, nil
}